<template>
  <div class="picture-manage-page">
    <a-card title="图片管理" :bordered="false">
      <!-- 搜索和筛选区域 -->
      <div class="search-area">
        <a-form layout="inline" :model="searchForm" @finish="handleSearch">
          <a-form-item label="搜索">
            <a-input
              v-model:value="searchForm.searchText"
              placeholder="输入图片名称或简介"
              style="width: 200px"
            />
          </a-form-item>
          <a-form-item label="分类">
            <a-select
              v-model:value="searchForm.category"
              placeholder="选择分类"
              style="width: 120px"
              allow-clear
            >
              <a-select-option v-for="category in categoryList" :key="category" :value="category">
                {{ category }}
              </a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item label="标签">
            <a-select
              v-model:value="searchForm.tags"
              mode="tags"
              placeholder="选择标签"
              style="width: 200px"
              allow-clear
            >
              <a-select-option v-for="tag in tagList" :key="tag" :value="tag">
                {{ tag }}
              </a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item label="审核状态">
            <a-select
              v-model:value="searchForm.reviewStatus"
              placeholder="选择审核状态"
              style="width: 120px"
              allow-clear
            >
              <a-select-option :value="0">待审核</a-select-option>
              <a-select-option :value="1">已通过</a-select-option>
              <a-select-option :value="2">已拒绝</a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item label="图片格式">
            <a-select
              v-model:value="searchForm.picFormat"
              placeholder="选择图片格式"
              style="width: 120px"
              allow-clear
            >
              <a-select-option value="jpg">JPG</a-select-option>
              <a-select-option value="png">PNG</a-select-option>
              <a-select-option value="gif">GIF</a-select-option>
              <a-select-option value="webp">WEBP</a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item>
            <a-button type="primary" html-type="submit">搜索</a-button>
            <a-button style="margin-left: 8px" @click="handleReset">重置</a-button>
          </a-form-item>
        </a-form>
      </div>

      <!-- 操作按钮区域 -->
      <div class="action-area">
        <a-space>
          <a-button type="primary" @click="handleAdd">
            <template #icon><plus-outlined /></template>
            新增图片
          </a-button>
          <a-button :disabled="!selectedRowKeys.length" @click="handleBatchDelete">
            <template #icon><delete-outlined /></template>
            批量删除
          </a-button>
        </a-space>
      </div>

      <!-- 图片列表表格 -->
      <div class="table-area">
        <a-table
          :columns="columns"
          :data-source="tableData"
          :pagination="pagination"
          :loading="loading"
          :row-selection="rowSelection"
          rowKey="id"
          @change="handleTableChange"
        >
          <!-- 图片列 -->
          <template #bodyCell="{ column, record }">
            <template v-if="column.key === 'url'">
              <a-image
                :width="80"
                :src="record.url"
                :preview="{
                  src: record.url,
                }"
              />
            </template>

            <!-- 标签列 -->
            <template v-else-if="column.key === 'tags'">
              <a-tag v-for="tag in record.tags" :key="tag" color="blue">
                {{ tag }}
              </a-tag>
            </template>

            <!-- 图片信息列 -->
            <template v-else-if="column.key === 'picInfo'">
              <a-tooltip placement="topLeft">
                <template #title>
                  格式：{{ record.picFormat }}<br />
                  尺寸：{{ record.picWidth }}×{{ record.picHeight }}<br />
                  比例：{{ record.picScale }}<br />
                  大小：{{ formatFileSize(record.picSize) }}
                </template>
                <span>
                  {{ record.picFormat }} | {{ record.picWidth }}×{{ record.picHeight }} |
                  {{ formatFileSize(record.picSize) }}
                </span>
              </a-tooltip>
            </template>
            <!-- 审核信息列 -->
            <template v-else-if="column.key === 'reviewInfo'">
              <a-tag :color="getReviewStatusColor(record.reviewStatus)">
                {{ getReviewStatusText(record.reviewStatus) }}
              </a-tag>
              <a-tooltip v-if="record.reviewMessage" placement="topLeft">
                <template #title>
                  审核意见：{{ record.reviewMessage }}<br />
                  审核人ID：{{ record.reviewerId || '-' }}
                </template>
                <span class="review-detail">（详情）</span>
              </a-tooltip>
            </template>

            <!-- 操作列 -->
            <template v-else-if="column.key === 'action'">
              <div class="action-buttons">
                <a-button type="link" size="small" @click="handleView(record)">查看</a-button>
                <a-button type="link" size="small" @click="handleEdit(record)">编辑</a-button>
                <a-popconfirm title="确定删除这张图片吗？" @confirm="handleDelete(record.id)">
                  <a-button type="link" size="small" danger>删除</a-button>
                </a-popconfirm>

                <!-- 根据审核状态显示不同的审核操作按钮 -->
                <div class="review-actions">
                  <template v-if="record.reviewStatus === 0">
                    <!-- 待审核状态：显示通过和拒绝按钮 -->
                    <a-button
                      type="link"
                      size="small"
                      @click="handleReview(record, 1)"
                      class="review-pass-btn"
                    >
                      通过
                    </a-button>
                    <a-button
                      type="link"
                      size="small"
                      @click="handleReview(record, 2)"
                      class="review-reject-btn"
                    >
                      拒绝
                    </a-button>
                  </template>
                  <template v-else-if="record.reviewStatus === 1">
                    <!-- 已通过状态：显示拒绝按钮 -->
                    <a-button
                      type="link"
                      size="small"
                      @click="handleReview(record, 2)"
                      class="review-reject-btn"
                    >
                      拒绝
                    </a-button>
                  </template>
                  <template v-else-if="record.reviewStatus === 2">
                    <!-- 已拒绝状态：显示通过按钮 -->
                    <a-button
                      type="link"
                      size="small"
                      @click="handleReview(record, 1)"
                      class="review-pass-btn"
                    >
                      通过
                    </a-button>
                  </template>
                </div>
              </div>
            </template>
          </template>
        </a-table>
      </div>
    </a-card>

    <!-- 图片详情模态框 -->
    <a-modal v-model:open="detailVisible" title="图片详情" width="800px" :footer="null">
      <div v-if="currentPicture" class="picture-detail">
        <div class="picture-preview">
          <a-image :src="currentPicture.url" :preview="false" />
        </div>
        <a-descriptions :column="2" bordered class="picture-info">
          <a-descriptions-item label="图片名称">
            {{ currentPicture.name }}
          </a-descriptions-item>
          <a-descriptions-item label="分类">
            {{ currentPicture.category || '-' }}
          </a-descriptions-item>
          <a-descriptions-item label="简介" :span="2">
            {{ currentPicture.introduction || '-' }}
          </a-descriptions-item>
          <a-descriptions-item label="标签">
            <a-tag v-for="tag in currentPicture.tags" :key="tag" color="blue">
              {{ tag }}
            </a-tag>
          </a-descriptions-item>
          <a-descriptions-item label="尺寸">
            {{ currentPicture.picWidth }} × {{ currentPicture.picHeight }}
          </a-descriptions-item>
          <a-descriptions-item label="比例">
            {{ currentPicture.picScale }}
          </a-descriptions-item>
          <a-descriptions-item label="格式">
            {{ currentPicture.picFormat }}
          </a-descriptions-item>
          <a-descriptions-item label="文件大小">
            {{ formatFileSize(currentPicture.picSize) }}
          </a-descriptions-item>
          <a-descriptions-item label="审核状态">
            <a-tag :color="getReviewStatusColor(currentPicture.reviewStatus)">
              {{ getReviewStatusText(currentPicture.reviewStatus) }}
            </a-tag>
          </a-descriptions-item>
          <a-descriptions-item label="审核意见" v-if="currentPicture.reviewMessage">
            {{ currentPicture.reviewMessage }}
          </a-descriptions-item>
          <a-descriptions-item label="创建时间">
            {{ formatDate(currentPicture.createTime) }}
          </a-descriptions-item>
          <a-descriptions-item label="更新时间">
            {{ formatDate(currentPicture.updateTime) }}
          </a-descriptions-item>
        </a-descriptions>
      </div>
    </a-modal>

    <!-- 图片编辑模态框 -->
    <a-modal
      v-model:open="editVisible"
      title="编辑图片"
      width="600px"
      @ok="handleSaveEdit"
      :confirm-loading="loading"
    >
      <a-form :model="editForm" layout="vertical">
        <a-form-item label="图片名称" name="name">
          <a-input v-model:value="editForm.name" />
        </a-form-item>

        <a-form-item label="简介" name="introduction">
          <a-textarea v-model:value="editForm.introduction" :rows="3" />
        </a-form-item>

        <a-form-item label="分类" name="category">
          <a-select v-model:value="editForm.category" placeholder="请选择分类" allow-clear>
            <a-select-option v-for="category in categoryList" :key="category" :value="category">
              {{ category }}
            </a-select-option>
          </a-select>
        </a-form-item>

        <a-form-item label="标签" name="tags">
          <a-select
            v-model:value="editForm.tags"
            mode="tags"
            placeholder="输入后回车或选择预置标签"
            style="width: 100%"
          >
            <a-select-option v-for="tag in tagList" :key="tag" :value="tag">
              {{ tag }}
            </a-select-option>
          </a-select>
        </a-form-item>
      </a-form>
    </a-modal>

    <!-- 图片审核模态框 -->
    <a-modal
      v-model:open="reviewVisible"
      title="图片审核"
      width="400px"
      @ok="handleSaveReview"
      :confirm-loading="reviewLoading"
    >
      <a-form :model="reviewForm" layout="vertical">
        <a-form-item label="审核结果" name="reviewStatus">
          <a-radio-group v-model:value="reviewForm.reviewStatus">
            <a-radio :value="1">通过</a-radio>
            <a-radio :value="2">拒绝</a-radio>
          </a-radio-group>
        </a-form-item>
        <a-form-item
          label="审核意见"
          name="reviewMessage"
          :rules="[{ required: reviewForm.reviewStatus === 2, message: '拒绝时必须填写审核意见' }]"
        >
          <a-textarea
            v-model:value="reviewForm.reviewMessage"
            :rows="3"
            placeholder="请输入审核意见，拒绝时必须填写"
          />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { message } from 'ant-design-vue'
import { PlusOutlined, DeleteOutlined } from '@ant-design/icons-vue'
import {
  deletePictureUsingPost,
  editPictureUsingPost,
  deletePicturesBatchUsingPost,
  doPictureReviewUsingPost,
  listPictureByPageUsingPost, updatePictureUsingPost
} from '@/api/pictureController'
import { listCategoryUsingPost } from '@/api/pictureCategoryController.ts'
import { listTagUsingPost } from '@/api/pictureTagController.ts'
import type { TableProps, TableColumnType } from 'ant-design-vue'

const router = useRouter()

// 搜索表单
const searchForm = reactive({
  searchText: '',
  category: undefined as string | undefined,
  tags: [] as string[],
  reviewStatus: undefined as number | undefined,
  picFormat: undefined as string | undefined,
})

// 表格数据
const tableData = ref<any[]>([])
const loading = ref(false)
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total: number) => `共 ${total} 条记录`,
})

// 当前排序字段和顺序
const sortState = reactive({
  sortField: 'createTime',
  sortOrder: 'descend'
})

// 标签和分类数据
const tagList = ref<string[]>([])
const categoryList = ref<string[]>([])

// 选中行
const selectedRowKeys = ref<number[]>([])

// 详情模态框
const detailVisible = ref(false)
const currentPicture = ref<any>(null)

// 审核模态框
const reviewVisible = ref(false)
const reviewLoading = ref(false)
const reviewForm = reactive({
  id: undefined as number | undefined,
  reviewStatus: 1, // 默认通过
  reviewMessage: '',
})

// 表格列定义
const columns: TableColumnType[] = [
  { title: '图片', key: 'url', width: 100, align: 'center' },
  { title: '名称', dataIndex: 'name', key: 'name', ellipsis: true },
  { title: '简介', dataIndex: 'introduction', key: 'introduction', ellipsis: true },
  { title: '分类', dataIndex: 'category', key: 'category', width: 100 },
  { title: '标签', key: 'tags', width: 200 },
  {
    title: '图片信息',
    key: 'picInfo',
    width: 180,
    ellipsis: true,
  },
  {
    title: '审核信息',
    key: 'reviewInfo',
    width: 160,
    ellipsis: true,
  },
  { 
    title: '创建时间', 
    dataIndex: 'createTime', 
    key: 'createTime', 
    width: 180, 
    sorter: true,
    defaultSortOrder: 'descend'
  },
  { title: '操作', key: 'action', width: 180, align: 'center', fixed: 'right' },
]

// 行选择配置
const rowSelection = computed<TableProps['rowSelection']>(() => ({
  selectedRowKeys: selectedRowKeys.value,
  onChange: (keys: number[]) => {
    selectedRowKeys.value = keys
  },
}))

// 获取标签和分类数据
const fetchTagCategories = async () => {
  try {
    // 获取所有分类
    const categoryRes = await listCategoryUsingPost({})
    if (categoryRes.data.code === 0) {
      categoryList.value = categoryRes.data.data?.map((item: any) => item.categoryName) || []
    }

    // 获取所有标签
    const tagRes = await listTagUsingPost({})
    if (tagRes.data.code === 0) {
      tagList.value = tagRes.data.data?.map((item: any) => item.tagName) || []
    }
  } catch (error) {
    console.error('获取标签分类失败:', error)
  }
}

// 获取图片列表
const fetchPictureList = async () => {
  loading.value = true
  try {
    const params = {
      current: pagination.current,
      pageSize: pagination.pageSize,
      searchText: searchForm.searchText,
      category: searchForm.category,
      tags: searchForm.tags,
      reviewStatus: searchForm.reviewStatus,
      picFormat: searchForm.picFormat,
      sortField: sortState.sortField,
      sortOrder: sortState.sortOrder,
    }

    const res = await listPictureByPageUsingPost(params)
    console.log('获取图片列表成功:', res.data.data)
    if (res.data.code === 0) {
      // 处理数据：解析 tags 字符串为数组
      const records = res.data.data?.records || []
      tableData.value = records.map((item: any) => {
        return {
          ...item,
          // 解析 tags 字符串为数组
          tags: typeof item.tags === 'string' ? JSON.parse(item.tags) : item.tags,
          // 确保 reviewStatus 是数字类型
          reviewStatus:
            typeof item.reviewStatus === 'string' ? parseInt(item.reviewStatus) : item.reviewStatus,
        }
      })
      pagination.total = res.data.data?.total || 0
    } else {
      message.error(res.data.message || '获取图片列表失败')
    }
  } catch (error) {
    console.error('获取图片列表失败:', error)
    message.error('获取图片列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.current = 1
  fetchPictureList()
}

// 重置搜索
const handleReset = () => {
  searchForm.searchText = ''
  searchForm.category = undefined
  searchForm.tags = []
  searchForm.reviewStatus = undefined
  searchForm.picFormat = undefined
  pagination.current = 1
  fetchPictureList()
}

// 表格变化（分页、排序）
const handleTableChange = (pag: any, filters: any, sorter: any) => {
  pagination.current = pag.current
  pagination.pageSize = pag.pageSize
  
  // 处理排序
  if (sorter.field) {
    sortState.sortField = sorter.field
    sortState.sortOrder = sorter.order === 'ascend' ? 'asc' : 'desc'
  } else {
    // 恢复默认排序
    sortState.sortField = 'createTime'
    sortState.sortOrder = 'desc'
  }
  
  fetchPictureList()
}

// 新增图片
const handleAdd = () => {
  router.push('/picture/create')
}

// 查看详情
const handleView = (record: any) => {
  // 处理 tags 和 reviewStatus 数据
  currentPicture.value = {
    ...record,
    tags: typeof record.tags === 'string' ? JSON.parse(record.tags) : record.tags,
    reviewStatus:
      typeof record.reviewStatus === 'string' ? parseInt(record.reviewStatus) : record.reviewStatus,
  }
  console.log('查看详情', currentPicture.value)
  detailVisible.value = true
}

// 编辑模态框
const editVisible = ref(false)
const editForm = reactive({
  id: undefined as number | undefined,
  name: '',
  introduction: '',
  category: undefined as string | undefined,
  tags: [] as string[],
})

// 打开编辑模态框
const handleEdit = (record: any) => {
  // 填充编辑表单数据
  editForm.id = record.id
  editForm.name = record.name
  editForm.introduction = record.introduction
  editForm.category = record.category
  editForm.tags = record.tags || []
  editVisible.value = true
}

// 保存编辑
const handleSaveEdit = async () => {
  if (!editForm.id) {
    message.warning('缺少图片ID')
    return
  }

  try {
    const res = await updatePictureUsingPost({
      id: editForm.id,
      name: editForm.name,
      introduction: editForm.introduction,
      category: editForm.category,
      tags: editForm.tags,
    })

    if (res.data.code === 0) {
      message.success('编辑成功')
      editVisible.value = false
      await fetchPictureList() // 重新获取列表数据
    } else {
      message.error(res.data.message || '编辑失败')
    }
  } catch (error) {
    console.error('编辑失败:', error)
    message.error('编辑失败')
  }
}

// 删除图片
const handleDelete = async (id: number) => {
  try {
    const res = await deletePictureUsingPost({ id })
    if (res.data.code === 0) {
      message.success('删除成功')
      await fetchPictureList()
    } else {
      message.error(res.data.message || '删除失败')
    }
  } catch (error) {
    console.error('删除失败:', error)
    message.error('删除失败')
  }
}

// 批量删除
const handleBatchDelete = async () => {
  if (selectedRowKeys.value.length === 0) {
    message.warning('请选择要删除的图片')
    return
  }

  try {
    loading.value = true
    const res = await deletePicturesBatchUsingPost({
      id: selectedRowKeys.value,
    })

    if (res.data.code === 0) {
      message.success('批量删除成功')
      // 清空选中项
      selectedRowKeys.value = []
      // 重新获取列表数据
      await fetchPictureList()
    } else {
      message.error(res.data.message || '批量删除失败')
    }
  } catch (error) {
    console.error('批量删除失败:', error)
    message.error('批量删除失败')
  } finally {
    loading.value = false
  }
}

// 处理审核按钮点击
const handleReview = (record: any, status: number) => {
  reviewForm.id = record.id
  reviewForm.reviewStatus = status
  reviewForm.reviewMessage = ''
  reviewVisible.value = true
}

// 保存审核结果
const handleSaveReview = async () => {
  if (!reviewForm.id) {
    message.warning('缺少图片ID')
    return
  }

  // 如果拒绝，必须填写审核意见
  if (reviewForm.reviewStatus === 2 && !reviewForm.reviewMessage.trim()) {
    message.warning('拒绝时必须填写审核意见')
    return
  }

  reviewLoading.value = true
  try {
    const res = await doPictureReviewUsingPost({
      id: reviewForm.id,
      reviewStatus: reviewForm.reviewStatus,
      reviewMessage: reviewForm.reviewMessage,
    })

    if (res.data.code === 0) {
      message.success('审核成功')
      reviewVisible.value = false
      await fetchPictureList() // 重新获取列表数据
    } else {
      message.error(res.data.message || '审核失败')
    }
  } catch (error) {
    console.error('审核失败:', error)
    message.error('审核失败')
  } finally {
    reviewLoading.value = false
  }
}

// 获取审核状态标签颜色
const getReviewStatusColor = (status: number) => {
  const colorMap = {
    0: 'orange',
    1: 'green',
    2: 'red',
  }
  return colorMap[status] || 'default'
}

// 获取审核状态文本
const getReviewStatusText = (status: number | string) => {
  const textMap: Record<string | number, string> = {
    0: '待审核',
    1: '已通过',
    2: '已拒绝',
    '0': '待审核',
    '1': '已通过',
    '2': '已拒绝',
  }
  const result = textMap[status]
  return result !== undefined ? result : '未知'
}

// 格式化文件大小
const formatFileSize = (bytes: number) => {
  if (bytes === 0) return '0 B'
  const k = 1024
  const sizes = ['B', 'KB', 'MB', 'GB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}

// 格式化日期
const formatDate = (dateString: string) => {
  if (!dateString) return '-'
  return new Date(dateString).toLocaleString()
}

// 初始化
onMounted(() => {
  fetchTagCategories()
  fetchPictureList()
})
</script>

<style scoped>
.picture-manage-page {
  padding: 24px;
}

.search-area {
  margin-bottom: 16px;
  padding: 16px;
  background: #fafafa;
  border-radius: 6px;
}

.action-area {
  margin-bottom: 16px;
}

.table-area {
  margin-top: 16px;
}

/* 操作按钮容器 */
.action-buttons {
  display: flex;
  flex-direction: column;
  gap: 2px;
  align-items: center;
}

/* 审核操作按钮容器 */
.review-actions {
  display: flex;
  gap: 4px;
  margin-top: 2px;
}

/* 审核通过按钮样式 */
.review-pass-btn {
  color: #52c41a !important;
}

/* 审核拒绝按钮样式 */
.review-reject-btn {
  color: #ff4d4f !important;
}

.picture-detail {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.picture-preview {
  text-align: center;
}

.picture-preview :deep(.ant-image) {
  max-width: 100%;
}

.picture-info {
  margin-top: 16px;
}

.review-detail {
  margin-left: 4px;
  color: #999;
  cursor: help;
}
</style>